package io.youngledo.usb.ui;

import io.youngledo.usb.util.DialogUtils;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;

import java.io.PrintWriter;
import java.io.StringWriter;

/// 异常堆栈对话框
///
/// 用于展示详细的异常信息和堆栈跟踪
public class ExceptionDialog extends Alert {

    /// 构造函数
    ///
    /// - **title**: 对话框标题
    /// - **message**: 简短的错误描述
    /// - **throwable**: 异常对象
    public ExceptionDialog(String title, String message, Throwable throwable) {
        super(AlertType.ERROR);

        setTitle(title);
        setHeaderText(message);
        setContentText(getSimpleMessage(throwable));

        // 创建可展开的异常详情区域
        String stackTrace = getStackTrace(throwable);

        Label label = new Label("异常详情：");

        TextArea textArea = new TextArea(stackTrace);
        textArea.setEditable(false);
        textArea.setWrapText(false);
        textArea.setMaxWidth(Double.MAX_VALUE);
        textArea.setMaxHeight(Double.MAX_VALUE);
        textArea.getStyleClass().add("exception-stacktrace");

        GridPane.setVgrow(textArea, Priority.ALWAYS);
        GridPane.setHgrow(textArea, Priority.ALWAYS);

        GridPane expContent = new GridPane();
        expContent.setMaxWidth(Double.MAX_VALUE);
        expContent.add(label, 0, 0);
        expContent.add(textArea, 0, 1);

        // 设置可展开内容
        getDialogPane().setExpandableContent(expContent);
        getDialogPane().setExpanded(true);

        // 设置对话框尺寸
        getDialogPane().setPrefWidth(800);
        getDialogPane().setPrefHeight(500);

        // 设置模态
        initModality(Modality.APPLICATION_MODAL);

        // 应用扁平化样式
        DialogUtils.applyFlatStyle(this);
    }

    /// 获取简短的异常消息
    ///
    private String getSimpleMessage(Throwable throwable) {
        if (throwable == null) {
            return "未知错误";
        }

        String message = throwable.getMessage();
        if (message != null && !message.isEmpty()) {
            return message;
        }

        return throwable.getClass().getSimpleName();
    }

    /// 获取完整的堆栈跟踪
    ///
    private String getStackTrace(Throwable throwable) {
        if (throwable == null) {
            return "无堆栈信息";
        }

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        throwable.printStackTrace(pw);
        return sw.toString();
    }

    /// 显示异常对话框（静态工厂方法）
    ///
    /// - **title**: 对话框标题
    /// - **message**: 简短的错误描述
    /// - **throwable**: 异常对象
    public static void show(String title, String message, Throwable throwable) {
        ExceptionDialog dialog = new ExceptionDialog(title, message, throwable);
        dialog.showAndWait();
    }

    /// 显示异常对话框（使用默认标题）
    ///
    /// - **message**: 简短的错误描述
    /// - **throwable**: 异常对象
    public static void show(String message, Throwable throwable) {
        show("错误", message, throwable);
    }
}